﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;

namespace customer.dao.V2
{
    public class SqlServerSchemaReader : SchemaReaderBase
    {

        public SqlServerSchemaReader(string connectionString)
        {   
            this.ConnectionString = connectionString;
        }

        public override SchemaResult GetSchema()
        {
            SchemaResult result = new SchemaResult();
            try
            {   
                using (SqlConnection conn = new SqlConnection(this.ConnectionString))
                {
                    conn.Open();

                    DataTable dtResult = conn.GetSchema();

                    List<Dictionary<string, object>> items = DATA_Util.DataTable2Dictionary(dtResult);

                    result.Data = items;
                }

                result.Success = true;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = ex.ToString();
            }

            return result;
        }

        public override SchemaResult GetSchema(string collectionName)
        {
            SchemaResult result = new SchemaResult();
            try
            {
                using (SqlConnection conn = new SqlConnection(this.ConnectionString))
                {
                    conn.Open();

                    DataTable dtResult = conn.GetSchema(collectionName);

                    List<Dictionary<string, object>> items = DATA_Util.DataTable2Dictionary(dtResult);

                    result.Data = items;
                }

                result.Success = true;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = ex.ToString();
            }

            return result;
        }

        public override SchemaResult GetSchema(string collectionName, string[] restrictionsArray)
        {
            SchemaResult result = new SchemaResult();
            try
            {
                using (SqlConnection conn = new SqlConnection(this.ConnectionString))
                {
                    conn.Open();

                    string cs = SqlClientMetaDataCollectionNames.Columns;

                    DataTable dtResult = conn.GetSchema(collectionName, restrictionsArray);

                    List<Dictionary<string, object>> items = DATA_Util.DataTable2Dictionary(dtResult);

                    result.Data = items;
                }

                result.Success = true;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = ex.ToString();
            }

            return result;
        }
        
        
    }
}
